/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Core;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.*;

/**
 *
 * @author LamHuynh
 */
public class Products {
    private String file;
    XPathFactory factory;
    XPath xpath;
    InputSource inputSource;
    public Products(String file)
    {
        this.file = file;
        this.factory = XPathFactory.newInstance();
        this.xpath = factory.newXPath();
        //InputStream resourceAsStream;
        //resourceAsStream        = "".getClass().getResourceAsStream(this.file);
        this.inputSource = new InputSource(file);
    }
    public ArrayList<Product> getListProducts()
    {
        String s = "";
        ArrayList<Product> listProduct = new ArrayList<Product>();
        try{
            XPathExpression expression = xpath.compile("/Products/Product");
            NodeList nodeList = (NodeList) expression.evaluate(inputSource, XPathConstants.NODESET);
            for( int i = 0, n = nodeList.getLength(); i < n; i++)
            {
                Node currentNode = nodeList.item(i);
                int Id = 0;
                String Name = "";
                int Quantity = 0;
                float Price = 0;

                for (int j = 0; j < currentNode.getChildNodes().getLength(); j++) {//Di qua tung phan tu cua customer
                    Node childNode = currentNode.getChildNodes().item(j);
                    if (childNode.getNodeName().equals("Id")) {//Tung thuoc tinh
                        Id = Integer.parseInt(childNode.getTextContent());
                    }
                    if (childNode.getNodeName().equals("Name")) {//Tung thuoc tinh
                        Name = childNode.getTextContent();
                    }
                    if (childNode.getNodeName().equals("Name")) {//Tung thuoc tinh
                        Name = childNode.getTextContent();
                    }
                    if (childNode.getNodeName().equals("Quantity")) {//Tung thuoc tinh
                        Quantity = Integer.parseInt(childNode.getTextContent());
                    }
                    if (childNode.getNodeName().equals("Price")) {//Tung thuoc tinh
                        Price = Float.parseFloat(childNode.getTextContent());
                    }
                }
                listProduct.add(new Product(Id, Name, Quantity, Price));
            }
        }
        catch(XPathExpressionException e)
        {
            s = e.getMessage();
        }
        return listProduct;
    }
}
